<?php

namespace control;
/*
*供应商价格本类
*/

use JetBrains\PhpStorm\NoReturn;

class supplierPriceListClass extends adIndexClass
{
    private const title         = '供应商价格本';
    private const page          = 'supplierPriceList';
    private const table         = 'store_supplier_price';
    private const tableSupplier = 'supplier';
    private const tableMaterial = 'material';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'supplierCode'    => [
                        'name'  => "供应商编码",
                        'width' => 200,
                    ],
                    'supplierName'    => [
                        'name'  => "供应商名称",
                        'width' => 200,
                    ],
                    'code'            => [
                        'name'  => "物料编码",
                        'width' => 150,
                    ],
                    'name'            => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'materialAliasNo' => [
                        'name'  => '供应商料号',
                        'width' => 150,
                        'sort'  => 1,
                    ],
                    'materialAlias'   => [
                        'name'  => '供应商品名',
                        'width' => 150,
                    ],
                    'model'           => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'            => [
                        'name'  => '单位',
                        'width' => 80,
                    ],
                    'price'           => [
                        'name'  => '采购单价(' . static::$unit . ')',
                        'width' => 150,
                        'sort'  => 1,
                    ],
                    'updateTime'      => [
                        'name'  => '更新时间',
                        'width' => 150,
                        'sort'  => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function supplierPriceOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "供应商编码" => text(array("name" => "code")) .
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "供应商名称" => text(array("name" => "name")),
                    '物料编码'  => text(array("name" => "materialCode")),
                ],
                [
                    '物料名称' => text(array("name" => "materialName")),
                    '规格型号' => text(array("name" => "model")),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 物料页卡价格本
     *
     * @return bool|string
     */
    public function supplierPrice(): bool|string
    {
        $html   = $this->supplierPriceOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function supplierPriceSearch(): bool|string
    {
        $materialId = $this->post('targetId');
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'coid'       => self::$coid,
            'materialId' => $materialId,
        ];
        // 客户搜索
        if ($this->post('code') || $this->post('name')) {
            $kWhere = search([
                "="    => $equal,
                "like" => [
                    'code' => $this->post('code'),
                    'name' => $this->post('name'),
                ],
            ]);
            $where  .= " AND `supplierId` IN (SELECT id FROM `supplier` WHERE 1=1 $kWhere)  ";
        }
        // 物料搜索
        if ($this->post('materialCode') || $this->post('materialName') || $this->post('model')) {
            $mWhere = search([
                "="    => $equal,
                "like" => [
                    'code'  => $this->post('materialCode'),
                    'name'  => $this->post('materialName'),
                    'model' => $this->post('model'),
                ],
            ]);
            $where  .= " AND `materialId` IN (SELECT id FROM `material` WHERE 1=1 $mWhere)  ";
        }
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $supplier   = query(self::tableSupplier, " id = '$array[supplierId]' ");
            $material   = query(self::tableMaterial, " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'supplierCode':
                        $row[] = $supplier['code'];
                        break;
                    case 'supplierName':
                        $row[] = $supplier['name'];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'], 'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='priceForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "供应商编码" => text(array("name" => "code")),
                    "供应商名称" => text(array("name" => "name")),
                    '物料编码'  => text(array("name" => "materialCode")),
                ],
                [
                    '物料名称' => text(array("name" => "materialName")),
                    '规格型号' => text(array("name" => "model")),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .= "<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'" . self::page . "'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'coid' => self::$coid,
        ];
        // 客户搜索
        if ($this->post('code') || $this->post('name')) {
            $kWhere = search([
                "="    => $equal,
                "like" => [
                    'code' => $this->post('code'),
                    'name' => $this->post('name'),
                ],
            ]);
            $where  .= " AND `supplierId` IN (SELECT id FROM `supplier` WHERE 1=1 $kWhere)  ";
        }
        // 物料搜索
        if ($this->post('materialCode') || $this->post('materialName') || $this->post('model')) {
            $mWhere = search([
                "="    => $equal,
                "like" => [
                    'code'  => $this->post('materialCode'),
                    'name'  => $this->post('materialName'),
                    'model' => $this->post('model'),
                ],
            ]);
            $where  .= " AND `materialId` IN (SELECT id FROM `material` WHERE 1=1 $mWhere)  ";
        }
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "box"  => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $supplier   = query(self::tableSupplier, " id = '$array[supplierId]' ");
            $material   = query(self::tableMaterial, " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'supplierCode':
                        $row[] = $supplier['code'];
                        break;
                    case 'supplierName':
                        $row[] = $supplier['name'];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'], 'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js() . clear;
        return json_encode($json, 320);
    }

    public function js()
    {
        return <<<eof
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
       $('#supplierPriceListAddMx').hide()
       $("#materialName").html(res.data.name);
       $("[name='materialId']").val(res.data.materialId);
    },'json');
}
</script>
eof;
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $name = materialClass::getName($info['materialId']);
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must . "物料：" => "<span id='materialName' class='exceed-ellipsis' style='max-width: 90%;'>$name</span>&nbsp;<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addMx',{})\">选择</span>" . hidden(array('name' => 'materialId', 'value' => $info['materialId'])),
                ),
                array(
                    must . "供应商：" => selectMultiple(["name" => "supplierId", 'value' => $info['supplierId'], 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' ", 'sqlField' => 'name', 'title' => '供应商名称']),
                    "供应商料号：" => text(array('name' => 'materialAliasNo', 'value' => $info['materialAliasNo'])),
                ),
                array(
                    "供应商品名：" => text(array('name' => 'materialAlias', 'value' => $info['materialAlias'])),
                    "采购单价：" => text(array('name' => 'price', 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($info['price'], 'pricePrecision'))),
                )
            ),
        ));
        return $this->layer(array("title" => "编辑", "height" => 250, "width" => 800, "html" => $html));
    }


    public function editEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            "supplierId"      => $this->post('supplierId'),
            "materialId"      => $this->post('materialId'),
            "materialAliasNo" => $this->post('materialAliasNo'),
            "materialAlias"   => $this->post('materialAlias'),
            "price"           => $this->post('price') ? self::formattingFigure($this->post('price'), 'pricePrecision') : '',
        ];
        $annotation = [
            'supplierId' => '供应商',
            'materialId' => '物料',
        ];
        $rules      = [
            'supplierId' => 'required',
            'materialId' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => "materialId = '$field[materialId]' and supplierId = '$field[supplierId]' and coid = '" . self::$coid . "'  and id !='$id'")) > 0) {
            $json['warn'] = '此供应商已存在此物料的价格本';
        } else {
            $material      = query('material', "id = '$field[materialId]'", "id,unit");
            $field['unit'] = $material['unit'];
            if (!$info['id']) {
                $field        = array_merge($field, [
                    'id'   => $id,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "where" => $where,
                    "field" => $field,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId     = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        } else {
            $exampleData[] = ['A供应商', '88', '钢板', '低合金结构钢钢板', 'GB3274-88', 'kg', 1];
            $excel         = $this->excelHead();
            $fileName      = self::title . '导入模板-' . importTemplateClass::getName($templateId) . '.xlsx';
            $filePath      = $excel->fileName($fileName, 'sheet1');
            $format        = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']) {
                    $backgroundStyle = null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])) {
                        //必填项判断
                        $backgroundStyle = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'], '', $backgroundStyle);
                    foreach ($exampleData as $y => $example) {
                        $exampleVal = match ($array['columnName']){
                            '供应商名称'=>$example[0],
                            '供应商料号'=>$example[1],
                            '供应商品名'=>$example[2],
                            '物料名称'=>$example[3],
                            '规格型号'=>$example[4],
                            '单位'=>$example[5],
                            '采购单价'=>$example[6],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了供应商价格本导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath, $fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId     = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x         = 0;
            $text      = '';
            $headArray = [];
            $row_list  = 0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i == 0) {
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $supplier   = query("supplier", "name = '$cell[供应商名称]' and coid = '" . self::$coid . "'");
                    $material   = query('material', "coid = '" . self::$coid . "' and name = '$cell[物料名称]' and model = '$cell[规格型号]' and state = '启用'");
                    $field      = [
                        'id'              => suiji(),
                        'coid'            => self::$coid,
                        'stid'            => self::$stid,
                        "supplierId"      => $supplier['id'],
                        "materialId"      => $material['id'],
                        "materialAliasNo" => $cell['供应商料号'],
                        "materialAlias"   => $cell['供应商品名'],
                        "unit"            => $cell['单位'] ?: $material['unit'],
                        "price"           => $cell['采购单价'] ? self::formattingFigure($cell['采购单价'], 'pricePrecision') : 0,
                    ];
                    $annotation = [
                        'supplierId' => '供应商',
                        'materialId' => '物料',
                    ];
                    $rules      = [
                        'supplierId' => 'required',
                        'materialId' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt     = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                    } elseif (!in_array($field['unit'], machiningOrderClass::unitOption($field['materialId']))) {
                        $text .= '\n第【' . $row_list . '】行此单位不在物料单位内';
                    } elseif (static::total(array('table' => self::table, 'where' => "materialId = '$field[materialId]' and supplierId = '$field[supplierId]' and coid = '" . self::$coid . "'")) > 0) {
                        $text .= "\n第【{$row_list}】行此供应商已存在此物料的价格本";
                    } else {
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * @return bool|string
     */
    public function addMx()
    {
        $html   =
            materialClass::typeSelect(name: 'type') .
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号"));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button));
    }

    /**
     *添加产品
     */
    public function addMxSearch()
    {
        $like        = [
            'a.name'          => $this->post('materialName'),
            'code'            => $this->post('code'),
            'model'           => $this->post('model'),
            'a.supplyControl' => '允许采购',
            'a.typePath'      => $this->post('type'),
        ];
        $equal       = [
            'a.coid'  => self::$coid,
            'a.state' => '启用',
        ];
        $where       = search(["like" => $like, "=" => $equal]);
        $page        = $this->page([
            "table"   => "material as a",
            "field"   => "a.*",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "a.`time` ASC",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $tr[] = ['', '分类', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $checkBox = "<input name='mxId' value='$array[id]' type='radio'>";
            $tr[]     = array(
                $checkBox,
                $materialObj::getTypePath($array['typeId']),
                $array['code'],
                $array['name'],
                $array['model']
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . space . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxId)) {
            $json['warn'] = '请选择物料';
        } else {
            $material     = query(self::tableMaterial, "id = '$mxId'", "id");
            $json['data'] = [
                'materialId' => $material['id'],
                'name'       => materialClass::getName($material['id']),
            ];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $supplier = query(self::tableSupplier, " id = '$array[supplierId]' ");
                $material = query(self::tableMaterial, " id = '$array[materialId]' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '供应商编码'=>$supplier['code'],
                            '供应商名称'=>$supplier['name'],
                            '物料编码'=>$material['code'],
                            '物料名称'=>$material['name'],
                            '供应商料号'=>$array['materialAliasNo'],
                            '供应商品名'=>$array['materialAlias'],
                            '规格型号'=>$material['model'],
                            '单位'=>$material['unit'],
                            '采购单价'=>self::lostZero($array['price'], 'pricePrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了供应商价格本";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "供应商价格本.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify = ''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '供应商名称',
                    'aliasName'  => '供应商名称',
                    'isMust'     => true,
                    'isRepeat'     => true,
                ],
                [
                    'columnName' => '供应商料号',
                    'aliasName'  => '供应商料号',
                    'isMust'     => false,
                ],
                [
                    'columnName' => '供应商品名',
                    'aliasName'  => '供应商品名',
                    'isMust'     => false,
                ],
                [
                    'columnName' => '物料名称',
                    'aliasName'  => '物料名称',
                    'isMust'     => true,
                    'isRepeat'     => true,
                ],
                [
                    'columnName' => '规格型号',
                    'aliasName'  => '规格型号',
                    'isMust'     => true,
                    'isRepeat'     => true,
                ],
                [
                    'columnName' => '单位',
                    'aliasName'  => '单位',
                    'isMust'     => false,
                ],
                [
                    'columnName' => '采购单价',
                    'aliasName'  => '采购单价',
                    'isMust'     => false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'供应商料号',
                    'aliasName'=>'供应商料号',
                ],
                [
                    'columnName'=>'供应商品名',
                    'aliasName'=>'供应商品名',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'采购单价',
                    'aliasName'=>'采购单价',
                ],
            ]
        };
    }
}
